package com.xnf.wemedia.filter;

import com.xnf.model.wemeida.pojos.WmUser;
import com.xnf.utils.WmThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xnf on 2022/3/30.
 */
@Order(1)
@Log4j2
@WebFilter(filterName = "wmTokenFilter" , urlPatterns = "/*")
public class WmTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String userId = request.getHeader("userId");
        WmUser wmUser = null;
        if (!StringUtils.isEmpty(userId)){
            wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtils.set(wmUser);
        }else{
            WmThreadLocalUtils.set(wmUser);
        }
        filterChain.doFilter(request,response);
    }
}
